const sleep = (delay) =>
  new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, delay);
  });

class ScrollNumber {
  /**
   *
   * @param {string} selector
   * @param {number} numberLength
   */
  constructor(selector, numberLength = 8) {
    this.$el = document.querySelector(selector);
    this.$els = [];
    this.timer = null;
    this.length = numberLength;
    this.$init();
  }
  // 初始化
  $init() {
    const container = document.createElement('div');
    container.className = 'number-container';

    for (let i = 0; i < this.length; i++) {
      const numberItem = document.createElement('div');
      const numberItemSpan = document.createElement('span');
      numberItem.className = 'number-container-item';
      numberItemSpan.innerText = '0123456789';
      numberItem.appendChild(numberItemSpan);
      container.appendChild(numberItem);
      this.$els[i] = { index: i, el: numberItemSpan, value: 0 };
    }
    this.$el.appendChild(container);
  }
  /**
   * 设置值,已节流处理
   * @param {number} number
   */
  setValue(number = 0) {
    let max = new Array(this.length);
    max = max.fill(9).join('') >>> 0;
    if (number > max) {
      console.error('数字超过显示');
      number = max;
    }
    if (this.timer) {
      clearTimeout(this.timer);
    }
    this.timer = setTimeout(() => {
      if (number < 0) {
        throw new Error('数字不能小于0');
      }
      if (number === 0) {
        // this.$els.forEach((item) => {
        //   item.el.style.transform = "translate(-50%,0)";
        // });
        const els = this.$els;
        for (const key in els) {
          if (Object.hasOwnProperty.call(els, key)) {
            const item = els[key];
            item.value = 0;
          }
        }
        return;
      }
      const values = number.toString().padStart(this.length, '0').split('');
      values.forEach((value, index) => {
        this.$els[index].value = value >>> 0;
      });
      this.$render();
      this.timer = null;
    }, 500);
  }
  async $render() {
    const els = this.$els;
    for (let i = els.length - 1; i >= 0; i--) {
      await sleep(100);
      const item = els[i];
      item.el.style.transform = `translate(-50%,-${item.value * 10}%)`;
    }
  }
}

(function iife() {
  const n1 = new ScrollNumber('.number', 8);
  setInterval(() => {
    n1.setValue(parseInt(Math.random() * 100000000));
  }, 1500);
  console.log(n1);
})();
